<?php
function user_url_home($username){
	return HOME.'member/'.$username;
}

function check_user_name(){
	$_SESSION['edit_userinfor']=0;
	if(isset($_SESSION['user'])){
		
		if($_SESSION['user']['username']=='undefined'||$_SESSION['user']['username']==''){
			$_SESSION['edit_userinfor']=1;
		
		}
		
		if($_SESSION['user']['email']=='undefined'||$_SESSION['user']['email']==''){
			$_SESSION['edit_userinfor']=1;
		}
	}
	

	if($_SESSION['edit_userinfor']==1){
			if($_GET['module']=='user'&&$_GET['act']=='thongtin'){
				
			}else{
			redirect(USER_INFO);
			}
	}

}
function user_login_session($data,$cookie=''){
							$_SESSION['user']['id'] = $data['id'];
							
							$_SESSION['user']['username']=$data['username'];
							$_SESSION['user']['name']=$data['name'];
							$_SESSION['user']['email']=$data['email'];
							$_SESSION['user']['changepass']=$data['changepass'];
							$_SESSION['user']['changename']=$data['changename'];
							$_SESSION['user']['facebook']=$data['facebook'];
							$_SESSION['user']['level']=$data['group_id'];
							$_SESSION['user']['upload']=$data['upload'];
							//GAN IP VA COOKIE CHO LOGIN NAY, TIME LA 5 NGAY----
							if($cookie!=1){
							$hash=md5(md5(get_ip().$data['email']));
							setcookie('truyencuatui_info_user',$data['username'], strtotime('+48 Hours'),"/");
							setcookie('truyencuatui_vn_valid',$hash,strtotime('+48 Hours'),"/");
							}
							// no cache - update php file source-------
							setcookie("lcache", "1", strtotime('+4 Hours'),"/");
							//--------------------------------------------------
						
							
							
							
}

function user_login(){
	$hp=new Helpers_Validation;
	$hp->check_empty($_POST['username'],"Tài khoản không được rỗng  ");
	$hp->check_empty($_POST['password'],"Mật khẩu không được rỗng ");
	$hp->check_username($_POST['username'],"Tài khoản chỉ bao gồm các ký tự, số và có độ dài từ 6 đến 35");
	
	if($hp->valid()){
			//Start Login --
				$muser=new Model_User;
				$u=$_POST['username'];
				$muser->login($u);
				if($muser->num_rows()==1)
				{
					$row=$muser->fetchOne();
					if($row['password']== sha1($_POST['password'])){
							if(USER_ACTIVE==1){
								if($row[active]==0){
									redirectjs("Tài Khoản của bạn chưa được kích hoạt, xin vui lòng kiểm tra email để kích hoạt tài khoản !",HOME);
									exit();
								}
							}
							$ip=get_ip();
							$row['ip']=$ip;
							$data=array("ip_login"=>$ip,
										"last_login"=>date("l m, y - g:h a")
										);
							$where="id=".$row['id'];
							$muser->update_user($data,$where);
							$row['logout']=LOGOUT;
							
							//GAN SESSION ----------
							user_login_session($row);
							redirect(user_url_home($_SESSION['user']['username']));
					}else{
					//Mat khau khong khop ---
					$data['error'][]="Mật khẩu của bạn không đúng !";
					
					}
				}else{
				// Username không thấy
				$data['error'][]="Tài khoản của bạn không tồn tại !";
				}
			//End Login --
	}else{ //Valid fail, return message error
		$data['error']=$hp->mess;
	}
	return $data;
}

function user_login_facebook($data){
							$muser=new Model_User;
							$ip=get_ip();
							$data2=array("ip_login"=>$ip,
										"date_login"=>date("Y-m-d h:i:s")
										);
							$where="id=".$data['id'];
							$muser->update_user($data2,$where);
							//---- Gan session
							user_login_session($data);
							
						echo "success";
						exit();
					
}
function user_add_facebook($data){

			//Start Login -- Kiem tra Username da ton tai chua, neu chua thi thi add, khong thi lay email la username luon
				$ip=get_ip();
				$muser=new Model_User;
				$result=$muser->check_user($data['username']);
				if($result){
					$user=$data['username']; // User name chua ton tai
				}else{
					$user=''; // User nam da ton tai , nen se dung email
				}
				// CHECK NAME CUA USER
				$result=$muser->check_name($data['name']);
				if($result){
					$name=$data['name']; // Name chua ton tai
				}else{
					$name=''; // Name nam da ton tai , nen se dung email
				}
				
					$dt=array("username"=>$user,
							"password"=>sha1($data['email']),
							"email"	  =>$data['email'],
							"name"=>$name,
							"date_registered"=>date('Y-m-d h:i:s'),
							"active"=>"1",
							"status"=>"1",
							"group_id"=>"4",
							"facebook_id"=>$data['facebook_id'],
							"facebook"=>"1",
							"ip_register"=>$ip
							);
				$muser->add_user($dt);
				
				$muser->where="username='".$user."'";
				$muser->get_user();
				$row=$muser->fetchOne();
				
				
				//-- Update infor login
				
				$data2=array("ip_login"=>$ip,
					"date_login"=>date("Y-m-d h:i:s")
				);
				$where="id=".$row['id'];
				$muser->update_user($data2,$where);
				// Asign session
				user_login_session($row);
				echo "success_add"; 
				exit();
				//---- GET USER INFOR FROM DATABASE
}


function get_user_by_username($user){
	$db=new db;
	$db->connect();
	$user=$db->security($user);
	$db->query("select * from users where username='".$user."'");
	$db->close();
	if($db->num_rows()>0){
		$dt= $db->fetchOne();
		if($dt['avatar']==''){
			$dt['avatar']='http://1.bp.blogspot.com/-7hfSMEAogKg/VKes1gtrmgI/AAAAAAAAF4I/JPIPaZ3r8FA/s0/default-avatar.jpg';
		}
		if($dt['slogan']==''){
			$dt['slogan']='No Status';
		}
		return $dt;
	
	}else{
	return false;
	}

}
function user_avatar($avatar){
	if($avatar !=''){
		return $avatar;
	}else{
		return "http://1.bp.blogspot.com/-7hfSMEAogKg/VKes1gtrmgI/AAAAAAAAF4I/JPIPaZ3r8FA/s0/default-avatar.jpg";
	}
}
function get_user_group_name($id){
		$re="";
		switch($id){
			case "1":$re="Administrator";break;
			case "2":$re="Smod";break;
			case "4":$re="Member";break;
			case "5":$re="Uploader";break;
			case "6":$re="Forum Moderator";break;
		}
		return $re;
}
function valid_facebook($facebook_token, $facebook_id,$email)
 {
  $ch = curl_init();
  $url="https://graph.facebook.com/me?access_token=".$facebook_token;
  curl_setopt($ch, CURLOPT_URL,$url );
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  // The following ensures SSL always works. A little detail:
  // SSL does two things at once:
  //  1. it encrypts communication
  //  2. it ensures the target party is who it claims to be.
  // In short, if the following code is allowed, CURL won't check if the
  // certificate is known and valid, however, it still encrypts communication.
  curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
  curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
  $result = curl_exec($ch);
  
  curl_close($ch);
  $fb_profile = json_decode( $result, true);

  if(isset($fb_profile['error'] ) )
  {
return false;
  }
  elseif( isset($fb_profile['id']) && $fb_profile['id'] != $facebook_id )//Check if this auth token has the same ID sent.
  {
	  return false;
 
  }
  if($fb_profile['email']!=$email){
  return false;
  }
return true;

 }
 
 function show_username($user,$name){
	if($name !='') return $name;
	return $user;
}
function user_url($username){
	return HOME.'member/'.$username;
}


function user_picasa_remote($url){
 													 if($url!=''){
														 $url_remote="http://up.manga24h.com/upload_remote.php?link=$url&server=picasa";
														 $data='';
														 $res= mycurl($data,$url_remote);
														 $res=json_decode($res,true);
														
															if($res['error']==false &&$res['url']!=''){
																
																return $res['url'];
															}else{
																//Doupload lan 2
																 sleep(2);
																 $url_remote="http://up.manga24h.com/upload_remote.php?link=$url&server=picasa";
																 $res= mycurl($data,$url_remote);
																 				
																 $res=json_decode($res,true);
																if($res['error']==false&&$res['url']!=''){
																		return $res['url'];
																
																}else{
																	return false;
																}
															}
													 }else{ //$URL !=''
													 	return false;
													 }
 }